package com.xiaochen.service.interceptor;

import com.alibaba.fastjson.JSON;
import com.xiaochen.model.entity.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户登录认证拦截器
 */
public class UserLoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler) throws Exception {
        // 如果token不为空，那么从redis中获取用户信息
        String token = request.getHeader("token");
        String userInfoJSON = redisTemplate.opsForValue().get("user:login:" + token);
        UserInfo userInfo = JSON.parseObject(userInfoJSON, UserInfo.class);
        // 将用户信息存储到ThreadLocal中
        if (userInfo != null) {
            AuthContextUtil.setUserInfo(userInfo);
        }
        return true;
    }
}